import Vue from 'vue'
// import { Loading } from 'element-ui'
// import '@/plugins/element.js'
import axios from 'axios'
import qs from 'qs'
import md5 from 'js-md5'
import store from '../store'
import router from '../router'
import { Notify } from 'vant';
// import router from 'router'
axios.defaults.timeout = 10000 // 超时10s
axios.defaults.baseURL = 'http://www.demo.com/'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// axios.defaults.crossDomain = true
// axios.defaults.withCredentials = true // 设置cross跨域 并设置访问权限 允许跨域携带cookie信息
// axios.defaults.headers.common['Authorization'] = '' // 设置请求头为 Authorization
// 配置发送请求前的拦截器 可以设置token信息
let loading = ''
const errMsg = 'timeout of 10000ms exceeded'
const filter = ['login', 'logout', 'register', 'test','getappid','index']
const nonceStr = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
// function startLoading () {
//   loading = Vue.prototype.$loading({
//     lock: true,
//     fullscreen: true
//   })
// }
// function endLoading () {
//   if (loading) loading.close()
// }
// 配置请求拦截器
axios.interceptors.request.use(config => {
  const action = config.url.split('/').pop().toLowerCase()
  // console.log(store.getters.token);
  const token = store.getters.token
  if (filter.indexOf(action) < 0 && (token === null || token === false)) {
    store.commit('login_out');
    router.push('/login');
    return Promise.reject(new Error('登录失效请重新登录'))
  }
  // loading开始
  // startLoading()
  config.headers.Authorization = token // 设置token
  return config
}, error => {
  // endLoading()
  return Promise.reject(error)
})

// 配置响应拦截器
axios.interceptors.response.use(res => {
  // loading结束
  // endLoading()

  // 这里面写所需要的代码
  if (res.data.code !== 200) {
    Notify({ type: 'danger', message: res.data.msg });
    if(res.data.msg == '登录态失败,请重新登录'){
      store.commit('login_out');
      router.push('/login');
    }
    return Promise.reject(new Error(res.data.msg))
  }
  // Vue.prototype.$message.success(res.data.msg)
  return Promise.resolve(res.data)
}, error => {
  // endLoading()
  if (error.message === errMsg) {
    return Promise.reject(new Error('请求超时'))
  }
  store.commit('login_out');
  router.push('/login');
  return Promise.reject(error)
}
)
/**
 * 集成所有请求方式
 * @param {String} method [请求方式get|post]
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function request (method, url, params) {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    let out = ''
    let nonce = ''
    const keys = Object.keys(params)
    const len = keys.length
    keys.sort()
    for (let index = 0; index < len; index++) {
      formData.append(keys[index], params[keys[index]])
      if (keys[index] === 'image' || keys[index] === 'file' || keys[index] === 'pic') {
          continue
        }
      out += `${keys[index]}=${params[keys[index]]}&`
    }
    for (let index = 0; index < 6; index++) {
      nonce += nonceStr[Math.floor(Math.random() * 62)]
    }
    // out += `nonceStr=${nonce}`
    formData.append('nonceStr', nonce)
    // 生成签名
    // out += `&sign=${md5(out)}`
    const sign = md5(out + 'nonceStr=' + nonce)
    formData.append('sign', sign)

    switch (method) {
      case 'get':
        axios.get(url, {
          params: qs.parse(out)
        }).then(res => {
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
        break
      case 'post':
        axios.post(url,  formData)
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
        break
      default:
        reject(new Error('请求方式不允许'))
        break
    }
  })
}